package com.dongqi.utils.ezviz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongqi.utils.HttpUtils;

/**
 * @Description 中江萤石云util类
 * @Date 2021-05-21
 * @Author dongqi
 */
public class ZJEzvizutil {

    private static final String appKey = "ab997d75b65e43398128b2459dec7a0e";

    private static final String appSecret = "1194868b8751f3380b1f34cd16d4b094";

    private static final String accessTokenUrl = "https://open.ys7.com/api/lapp/token/get";

    private static final String videoAddressUrl = "https://open.ys7.com/api/lapp/v2/live/address/get";

    private static AccessToken accessToken;

    private static void getToken() {
        String params = "appKey=" + appKey + "&appSecret=" + appSecret;
        String result = HttpUtils.sendPost(accessTokenUrl, params);
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.getString("code");
        if ("200".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.getString("accessToken");
            long expireTime = data.getLongValue("expireTime");
            //创建token对象，并存储
            accessToken = new AccessToken(token, expireTime);
        }
    }

    /**
     * 向外提供access_token的方法
     *
     * @return
     */
    public static String getAccessToken() {
        if (accessToken == null || accessToken.isExpired()) {
            getToken();
        }
        return accessToken.getAccessToken();
    }


    /**
     * 获取视频数据
     *
     * @param deviceSerial 设备序列号
     * @param channelNo    通道号
     * @param protocol     流播放协议 1-ezopen、2-hls、3-rtmp、4-flv
     * @return
     */
    public static JSONObject getVideoData(String deviceSerial, Integer channelNo, Integer protocol) {
        String accessTokenStr = getAccessToken();
        if (protocol == null) {
            protocol = 1;
        }
        if (channelNo == null) {
            channelNo = 1;
        }
        String params = "accessToken=" + accessTokenStr + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo + "&protocol=" + protocol;
        String result = HttpUtils.sendPost(videoAddressUrl, params);
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.getString("code");
        if ("200".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            return data;
        }
        return null;
    }
}
